import styles from './ballCard.module.scss';
import { GiBasketballJersey } from 'react-icons/gi';
import { IPropsBall } from './ballCard.types';
import Button from '../button/button';
import { addToFavorite } from '../../store/balls/balls.slice';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { fetchCartPostSlice } from '../../store/cart/cart.actions';
import { addBallToCart, deleteBallOnCart } from '../../store/cart/cart.slice';


export const BallCard = ({ ball }: IPropsBall) => {
	const {token} = useAppSelector(state => state.authorization.user);
	const {balls} = useAppSelector(state => state.cart);
	const dispatch = useAppDispatch();
	const addBallOnCart = (e: React.MouseEvent<HTMLButtonElement>) => {
		e.stopPropagation();
		// dispatch(fetchCartPostSlice(ball));
		{hasOnCart === true ? dispatch(deleteBallOnCart(ball.id)): dispatch(addBallToCart(ball));}
		
	};
	const hasOnCart = balls.some(item => item.id === ball.id);

	return (
		<div className={styles.ball_cart} onClick={() => console.log(ball.id)}>
			<span
				onClick={(e) => {
					e.stopPropagation(),
					console.log('click'),
					dispatch(addToFavorite(ball.id));
				}}
				className={styles.form}
			>
				<GiBasketballJersey
					color={ball.favorite ? '#ff0000' : '#ffa500'}
					size={40}
				/>
			</span>
			<div>
				<div className={styles.img}>
					<img src={ball.image} width={300} />
				</div>
				<div className={styles.price}>
					<p>Цена {ball.price} р</p>
					<Button deleted={hasOnCart ? true : false} disabled={token !== null ? false : true} onClick={addBallOnCart} appearance="small">
						{hasOnCart !== true ? 'В корзину': 'Удалить'}
					</Button>
				</div>
				<div className={styles.description}>
					<p className={styles.item}>Описание:</p>
					<p>{ball.title}</p>
				</div>
			</div>
		</div>
	);
};
